clear all
set more off
version 15.1
if "`c(username)'"=="mbusso"  {
	global dir =  "C:\Dropbox\Stated Preferences\Replication Package\" 		
	}
if "`c(username)'"=="Hernan"  {
	global dir =  "C:\Dropbox\Stated Preferences\Replication Package\" 		
} 
if "`c(username)'"=="juanf"  {
	global dir =  "D:\Dropbox\Stated Preferences\Replication Package\" 		
} 
else {
	global dir =  /* "Your Directory " */ 		
} 

run "$dir/Scripts/insertrow.ado"
run "$dir/Scripts/swaprows.ado"
qui do "$dir/Scripts/TexEdits.do"

********************************************************************************
//globals for regressions
global cov_dem "age female secondary_complete employment_situation ln_monthly_income_ppp2019 i.imputed_income married children top50pcent_earner" 
global balance "age female secondary_complete employment_situation ln_monthly_income_ppp2019 married number_children children"
global cov_games "i.pgprop i.rgprop" 

********************************************************************************
//// Analysis of Vignettes
use "$dir/Data/final.dta", clear 
// Gen Variables
*Traetments
* Inital Public/private characteristic
gen initial_private_school = inlist(vigroup,5,6,7,8), after(vigroup)
gen initial_private_hospital = inlist(vigroup,1,2,3,4), after(initial_private_school)
* Income
gen high_income_school = inlist(vigroup,3,4,7,8), after(initial_private_hospital)
gen high_income_hospital = inlist(vigroup,1,2,5,6), after(high_income_school)
* Quality
gen high_quality_school = inlist(vigroup,2,4,6,8), after(high_income_hospital)
gen high_quality_hospital = inlist(vigroup,1,3,5,7), after(high_quality_school)
*Outcomes
* Final Public/private characteristic
gen final_private_school = (vi1a_group14 == 2) | (vi1a_group58 == 1), after(high_quality_hospital)
gen final_private_hospital = (vi2a_group14 == 1) | (vi2a_group58 == 2), after(final_private_school)
* How much would pay for private option
gen willingness_pay_private_school = vi1b/ppp_pc_2019, after(final_private_hospital)
gen willingness_pay_private_hospital = vi2b/ppp_pc_2019, after(willingness_pay_private_school)
*Stated Institutional Trust
*school
xtile it2_half = it2, nq(2)
gen high_school_trust = .
replace high_school_trust = 1 if it2_half == 2
replace high_school_trust = 0 if it2_half == 1
*hospital
xtile it3_half = it3, nq(2)
gen high_hospital_trust = .
replace high_hospital_trust = 1 if it3_half == 2
replace high_hospital_trust = 0 if it3_half == 1
 * Continuous trust variables
gen trust_school   = it2
gen trust_hospital = it3
* Quadratic terms
gen trust_school_2   = trust_school^2
gen trust_hospital_2 = trust_hospital^2

*************************************** Pre-treatment balance. (Figure 1) *****************************************************

//means and differences
 global balance "age female secondary_complete employment_situation ln_monthly_income_ppp2019 married number_children children trust_school trust_hospital"
 local V: word count $balance
 
 //means
 tabstat $balance, by(vigroup) format(%9.2f) notot save 
 matrix M = r(Stat1)', r(Stat2)', r(Stat3)', r(Stat4)', r(Stat5)', r(Stat6)', r(Stat7)', r(Stat8)' 
 
 //pvalues
 matrix P= J(`V',8,.)
 local v = 1
 foreach var in $balance{
   ereturn clear
   areg `var' i.vigroup, a(country)
   testparm i.vigroup
   matrix P[`v',1] = r(p)
   forvalues g = 2/8{
   	 testparm `g'.vigroup
	 matrix P[`v',`g'] = r(p)
   }
   local ++v
 }
matlist P

//compilation
preserve
 drop _all 
 svmat M
 svmat P
 
 gen Variables=""
 order Variables
 replace Variables="Age" if _n==1 
 replace Variables="Female" if _n==2
 replace Variables="Secondary Educ. Comp." if _n==3
 replace Variables="Employed" if _n==4
 replace Variables="Monthly Income (US dollars, logs)" if _n==5 
 replace Variables="Married" if _n==6
 replace Variables="Number of Children" if _n==7 
 replace Variables="% of respondents with at least one kid" if _n==8 
 replace Variables="Stated Public School Trust" if _n==9
 replace Variables="Stated Public Hospital Trust" if _n==10 
 
 insertrow, place(before) row(1)
 
 replace Variables="Baseline Covariates         " if _n==1
 
 forvalues j = 1/8{
   gen aux = string(M`j', "%9.2f")
   replace aux = "" if aux=="."
   drop M`j'
   ren aux M`j'
 }
 
order Variables M1 M2 M3 M4 M5 M6 M7 M8
forvalues i = 1/8{
  label var M`i' "Group `i' Mean"
}
label var P1 "p-value omnibus"
forvalues i = 2/8{
   label var P`i' "p-value G1 vs. G`i'"
}

insobs 1, before(1)
gen n = _n

local N = _N
forvalues i = 1/`N' {
	local val = n[`i']
	local name = Variables[`i']
	label define varnames `val' "`name'", modify
}

label values n varnames
*rename (A4 A5) (PValueCvsfemale PValueCvsmale)

twoway (scatter n P1, mcolor(black) msize(medium) msymbol(smcircle)) ///
	   (scatter n P2, mcolor(dkorange) msize(small) msymbol(circle_hollow)) ///
	   (scatter n P3, mcolor(cranberry) msize(small) msymbol(triangle)) ///
	   (scatter n P4, mcolor(ebblue) msize(small) msymbol(triangle_hollow))  /// 
	   (scatter n P5, mcolor(navy) msize(small) msymbol(smsquare)) ///
	   (scatter n P6, mcolor(gs8) msize(small) msymbol(square_hollow)) ///
	   (scatter n P7, mcolor(lime) msize(small) msymbol(diamond)) ///
	   (scatter n P8, mcolor(lavender) msize(small) msymbol(diamond_hollow))  /// 
	   , ///
	   xlabel(0 0.05 0.1 1, notick labs(medsmall)) ///
	   xtitle("p-value", size(medsmall)) ///
	   ylabel(2(1)12, val notick labs(medsmall) format(%9.2f) labgap(*3) angle(horizontal)) ///
	   yscale(rev r(3(1)10))  ytitle("") ///
	   xline(0.05, lp(dot) lc(black) lw(medthin)) ///
	   xline(0.1, lp(dot) lc(black) lw(medthin)) ///
	   graphr(fcolor(white) lcolor(white) ifcolor(white) ilcolor(white))  ///
	   legend(order(1 "Omnibus P-value" 2 "Group 1 vs. Group 2" 3 "Group 1 vs. Group 3" ///
	   4 "Group 1 vs. Group 4" 5 "Group 1 vs. Group 5" 6 "Group 1 vs. Group 6" ///
	   7 "Group 1 vs. Group 7" 8 "Group 1 vs. Group 8" ) pos(6) col(2))	 ///
	   graphregion(margin(l=0 t=0 r=0 b=0)) 
graph export "$dir/Results/balance.pdf", as(pdf) replace	   
restore


 
 *********  Marginal effects ofservice quality, income, and provider type on choices and willingness to pay. (Table 2) ************
 
 ////// Treatments: Being Assigned High Income, High Quality and Private Option 
///// Models


local i = 1
local mode replace

foreach institution in school hospital {
    foreach outcome in final willingness_pay {

        * Control group mean and SD
        quietly sum `outcome'_private_`institution' if ///
            initial_private_`institution' == 0 & ///
            high_income_`institution'     == 0 & ///
            high_quality_`institution'    == 0
        local mean = r(mean)
        local sd   = r(sd)

        * Main regression
        areg `outcome'_private_`institution' ///
            i.high_quality_`institution'##i.high_income_`institution'##i.initial_private_`institution' ///
            $cov_dem $cov_games, absorb(country)
        local N = e(N)

        * Marginal effects 
        margins high_quality_`institution'##high_income_`institution'##initial_private_`institution'
        estpost margins initial_private_`institution'##high_income_`institution'##high_quality_`institution'
		
		* Test Quality Diferences
        test ///
            (0.initial_private_`institution'#0.high_income_`institution'#0.high_quality_`institution') = ///
            (0.initial_private_`institution'#0.high_income_`institution'#1.high_quality_`institution')
		local p1 : display %9.3f = r(p)

        test ///
            (0.initial_private_`institution'#1.high_income_`institution'#0.high_quality_`institution') = ///
            (0.initial_private_`institution'#1.high_income_`institution'#1.high_quality_`institution')
        local p2 : display %9.3f = r(p)

        test ///
            (1.initial_private_`institution'#0.high_income_`institution'#0.high_quality_`institution') = ///
            (1.initial_private_`institution'#0.high_income_`institution'#1.high_quality_`institution')
        local p3 : display %9.3f = r(p)

        test ///
            (1.initial_private_`institution'#1.high_income_`institution'#0.high_quality_`institution') = ///
            (1.initial_private_`institution'#1.high_income_`institution'#1.high_quality_`institution')
        local p4 : display %9.3f = r(p)
		
		* Test Income Differences

		* Public default, low quality
		test ///
			(0.initial_private_`institution'#0.high_income_`institution'#0.high_quality_`institution') = ///
			(0.initial_private_`institution'#1.high_income_`institution'#0.high_quality_`institution')
		local q1 : display %9.3f r(p)

		* Public default, high quality
		test ///
			(0.initial_private_`institution'#0.high_income_`institution'#1.high_quality_`institution') = ///
			(0.initial_private_`institution'#1.high_income_`institution'#1.high_quality_`institution')
		local q2 : display %9.3f r(p)

		* Private default, low quality
		test ///
			(1.initial_private_`institution'#0.high_income_`institution'#0.high_quality_`institution') = ///
			(1.initial_private_`institution'#1.high_income_`institution'#0.high_quality_`institution')
		local q3 : display %9.3f r(p)

		* Private default, high quality
		test ///
			(1.initial_private_`institution'#0.high_income_`institution'#1.high_quality_`institution') = ///
			(1.initial_private_`institution'#1.high_income_`institution'#1.high_quality_`institution')
		local q4 : display %9.3f r(p)
				
        * Conditional outreg options
        if "`outcome'" == "willingness_pay" {
            local outregopts "dec(1) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
        }
        else {
            local outregopts "dec(3) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
        }

        * Export marginal effects table
        outreg2 using "$dir/Results/Marginal_Effects.xml", `mode' `outregopts'  ///
            addstat("Control mean", `mean', "Control S.D.", `sd', "Observations", `N') ///
			addtext("\$ H_0: [1] = [2]\$","`p1'","\$ H_0: [3] = [4]\$","`p2'","\$ H_0: [1] = [3]\$", ///
			"`q1'","\$ H_0: [2] = [4]\$","`q2'","\$ H_0: [5] = [6]\$","`p3'","\$ H_0: [7] = [8]\$","`p4'", ///
			"\$ H_0: [5] = [7]\$","`q3'","\$ H_0: [6] = [8]\$","`q4'")

        local mode append
        local i = `i' + 1
    }
}


 preserve
 use "$dir/Results/Marginal_Effects_dta.dta", clear
 gen n = _n
 drop if inrange(n,1,2) | inrange(n,4,39) | inrange(n,56,91) | inrange(n,118,119)
 forvalues i = 4/5{
 	replace v`i' = v`i'[_n+16] if _n>=2 & _n<=17
 }
 drop if inrange(n,92,107)

 replace v1="[1] Public × Low Income × Low Quality" if v1=="0bn.initial_private_school#0bn.high_income_school#0bn.high_quality_school" 
 replace v1="[2] Public × Low Income × High Quality" if v1=="0bn.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="[3] Public × High Income × Low Quality" if v1=="0bn.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="[4] Public × High Income × High Quality" if v1=="0bn.initial_private_school#1.high_income_school#1.high_quality_school"
 replace v1="[5] Private × Low Income × Low Quality" if v1=="1.initial_private_school#0bn.high_income_school#0bn.high_quality_school"
 replace v1="[6] Private × Low Income × High Quality" if v1=="1.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="[7] Private × High Income × Low Quality" if v1=="1.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="[8] Private × High Income × High Quality" if v1=="1.initial_private_school#1.high_income_school#1.high_quality_school"
 
 replace n = 47.5 in 20
 replace n = 47.6 in 21
 replace n = 47.7 in 22
 replace n = 47.8 in 23
 replace n = 55.5 in 24
 replace n = 55.6 in 25
 replace n = 55.7 in 26
 replace n = 55.8 in 27
 sort n
 
 insobs 3
 
 replace v1="Socio-demographic" if _n==29
 replace v1="Other games" if _n==30
 
 forvalues i = 2/5{
 	replace v`i'="Yes" if _n==29 | _n==30
 }

 local h=1 
 foreach i in 2 3 4 5{
	label var v`i' "(`h')"
	local ++h
 }  
 
 insobs 1, before(2)
 insobs 1, before(15)
 
 replace v1="\textit{Panel A: Public Default}" in 2
 replace v1="\cline{2\--3} \cline{4\--5} \textit{Panel B: Private Default}" in 15
 
 replace v1="\hspace{8pt} "+v1 if inlist(_n,3,5,7,9,11,12,13,14,16,18,20,22,24,25,26,27)
 replace v1="\addlinespace "+v1 if inlist(_n,3,11,15,16,24)
 drop in 1
 
   # delimit ;	
 texsave v* using "$dir/Results/Marginal_Effects.tex",
 headerlines("
  & \multicolumn{2}{c}{School} & \multicolumn{2}{c}{Hospital} \\\cline{2-3}\cline{4-5}\addlinespace
  & Chooses Private & Willingness to Pay & Chooses Private & Willingness to Pay \\\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\addlinespace
  & (1) & (2) & (3) & (4) \\\addlinespace\hline
 ")  
 replace align(l@{\extracolsep{4pt}}cccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Marginal_Effects.tex")
 #delimit cr
 restore
 
 
   ***************************** Heterogeneous marginal effects: Stated institutional trust. (Table 3) *******************************
 
 ////// Treatments: Being Assigned High Income, High Quality and Private Option 
///// Models

	
local i=1
local mode replace

foreach institution in school hospital {
    foreach outcome in final willingness_pay {
        forvalues high = 0/1 {
			
			* Control group mean and SD
            quietly sum `outcome'_private_`institution' if ///
                initial_private_`institution' == 0 & ///
                high_income_`institution'     == 0 & ///
                high_quality_`institution'    == 0 & ///
                high_`institution'_trust      == `high'
            local mean = r(mean)
            local sd   = r(sd)

            * Main regression
            areg `outcome'_private_`institution' ///
                i.high_quality_`institution'##i.high_income_`institution'##i.initial_private_`institution' ///
                $cov_dem $cov_games if high_`institution'_trust == `high', absorb(country)
            local N = e(N)

            * Marginal Effects
            margins high_quality_`institution'##high_income_`institution'##initial_private_`institution' ///
                if high_`institution'_trust == `high'
            estpost margins initial_private_`institution'##high_income_`institution'##high_quality_`institution'
			

            * outreg2 options 
            if "`outcome'" == "willingness_pay"{
                local outregopts "dec(1) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
            }
            else {
                local outregopts "dec(3) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
            }

            * Export marginal effects
            outreg2 using "$dir/Results/Marginal_Effects_Institutional_Trust.xml", `mode' `outregopts' ///
                addstat("Control mean", `mean', "Control S.D.", `sd', "Observations", `N')

            local mode append
            local i = `i'+1
        }
    }
}


 preserve
 use "$dir/Results/Marginal_Effects_Institutional_Trust_dta.dta", clear
 gen n = _n
 drop if inrange(n,1,2) | inrange(n,4,39) | inrange(n,56,91) | inrange(n,110,111)
 forvalues i = 6/9{
 	replace v`i' = v`i'[_n+16] if _n>=2 & _n<=17
 }
 drop if inrange(n,92,107)
 

 replace v1="Public × Low Inc. × Low Qual." if v1=="0bn.initial_private_school#0bn.high_income_school#0bn.high_quality_school" 
 replace v1="Private × Low Inc. × Low Qual." if v1=="1.initial_private_school#0bn.high_income_school#0bn.high_quality_school"
 replace v1="Public × High Inc. × Low Qual." if v1=="0bn.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="Public × Low Inc. × High Qual." if v1=="0bn.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="Private × High Inc. × Low Qual." if v1=="1.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="Private × Low Inc. × High Qual." if v1=="1.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="Public × High Inc. × High Qual." if v1=="0bn.initial_private_school#1.high_income_school#1.high_quality_school"
 replace v1="Private × High Inc. × High Qual." if v1=="1.initial_private_school#1.high_income_school#1.high_quality_school"
 
 
 insobs 3
 
 replace v1="Socio-demographic" if _n==21
 replace v1="Other games" if _n==22
 
 forvalues i = 2/9{
 	replace v`i'="Yes" if _n==21 | _n==22
 }

 local h=1 
 foreach i in 2 3 4 5 6 7 8 9{
	label var v`i' "(`h')"
	local ++h
 }  
 
 insobs 1, before(2)
 insobs 1, before(11)
 
 replace v1="\textit{Panel A: Public Default}" in 2
 replace v1="\cline{2\--5} \cline{6\--9} \textit{Panel B: Private Default}" in 11
 
 replace v1="\hspace{8pt} "+v1 if inlist(_n,3,5,7,9,12,14,16,18)
 replace v1="\addlinespace "+v1 if inlist(_n,3,12)
 drop in 1
 
   # delimit ;	
 texsave v* using "$dir/Results/Marginal_Effects_Institutional_Trust.tex",
 headerlines("
  & \multicolumn{4}{c}{School} & \multicolumn{4}{c}{Hospital} \\\cline{2-5}\cline{6-9}\addlinespace
  & \multicolumn{2}{c}{Chooses Private} & \multicolumn{2}{c}{Willingness to Pay} & \multicolumn{2}{c}{Chooses Private} &  \multicolumn{2}{c}{Willingness to Pay} \\\cline{2-3}\cline{4-5}\cline{6-7}\cline{8-9}\addlinespace
  & Low IT & High IT & Low IT & High IT & Low IT & High IT & Low IT & High IT \\\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6}\cline{7-7}\cline{8-8}\cline{9-9}\addlinespace
  & (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8) \\\addlinespace\hline
 ")  
 replace align(l@{\extracolsep{4pt}}cccccccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Marginal_Effects_Institutional_Trust.tex")
 #delimit cr
 restore
 
  ************************************ Sample descriptive statistics. (Table A1) ************************************

//import

 global balance "age female secondary_complete employment_situation ln_monthly_income_ppp2019 married number_children children"
 local V: word count $balance

 matrix P= J(`V',1,.)
 //means (no weight)
 tabstat $balance , format(%9.2f) stats(mean n) save
 matrix M = r(StatTotal)'
 //means
 tabstat $balance [aw=wt2], format(%9.2f) stats(mean n) save
 matrix W = r(StatTotal)'
 //compilation
 preserve
 matrix A= M, W \J(2,4,.)
 drop _all
 svmat A

 //order
 *Rename variables
 gen Variables= ""
 order Variables
 gen n=_n
 replace Variables="Age" if n==1
 replace Variables="Female" if n==2
 replace Variables="Secondary Educ. Comp." if n==3
 replace Variables="Employed" if n==4
 replace Variables="Monthly Income (US dollars)" if n==5
 replace Variables="Married" if n==6
 replace Variables="Number of Children" if n==7
 replace Variables="\% of respondents with at least one kid" if n==8
 replace Variables="Number of obs." if n==9
 drop n

 //merge with HHSurvey average 
 merge 1:1 Variables using "$dir/Data/HHSurvey_all.dta"  

 //order the rows
 swaprows, swap(3) and(4)
 swaprows, swap(9) and(4)
 swaprows, swap(6) and(7)   
 swaprows, swap(7) and(10)
 swaprows, swap(8) and(9)
 swaprows, swap(9) and(10)

 // # of observations in the last row
 drop _merge
 replace A1=7229 if _n==10
 replace A3=7229 if _n==10
 drop A2 A4

 rename A1 nw_mean
 rename A3 w1_mean
 rename ALL_m hh_mean

 //string variables with 2 decimals
 foreach j in nw w1 hh{
	gen aux = string(`j'_mean, "%10.2f")
	replace aux = "" if aux=="."
	drop `j'_mean
	ren aux `j'_mean
 }

 order Variables nw_mean w1_mean hh_mean 

 replace nw_mean="7229" if _n==10
 replace w1_mean="7229" if _n==10
 replace hh_mean="800825"  if _n==10

 //name column names for latex
 gen n=_n 
 label var nw_mean "Mean"
 label var w1_mean "Weighted Mean (age-gender-education)"
 label var hh_mean "Weighted Mean"
 
 drop in 1
 drop in 8/9
 drop n
 replace Variables = "\hline \addlinespace " + Variables in 1

  # delimit ;	
 texsave using "$dir/Results/Table_Descrip_Surveys.tex",
 headerlines("
 & \multirow{2}{*}{Mean} & Weighted Mean & Weighted Mean \\\addlinespace
 && (age-gender-education) & (Household Surveys) \\\cline{2-2}\cline{3-3}\cline{4-4} \addlinespace
 & (1) & (2) & (3) \\
 ") 
 replace align(l@{\extracolsep{4pt}}ccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Table_Descrip_Surveys.tex")
 restore
 
   *************************** Sample descriptive statistics by country. (Table A2) ******************************
preserve
  foreach x in AR BR CL CO MX PE{
  //import
  use "$dir/Data/final.dta", clear 
  local V: word count $balance
  global balance "age female secondary_complete employment_situation monthly_income_ppp2019 married number_children children"
  local V = `V'
   matrix P= J(`V',1,.)
   //means (no weight)
   tabstat $balance if country=="`x'", format(%9.2f) stats(mean n) save
   matrix M_`x' = r(StatTotal)'
   //means using wt1 
   tabstat $balance [aw=wt] if country=="`x'", format(%9.2f) stats(mean n) save
   matrix W_`x' = r(StatTotal)'
   //means using wt2
   tabstat $balance [aw=wt2] if country=="`x'", format(%9.2f) stats(mean n) save
   matrix W2_`x' = r(StatTotal)'
   //compilation
   matrix A_`x'= M_`x', W_`x',W2_`x' \J(2,6,.)
   drop _all
   svmat A_`x'
   
   //order
   *Rename variables
   gen Variables= ""
   order Variables
   gen n=_n
   replace Variables="Age" if n==1
   replace Variables="Female" if n==2
   replace Variables="Secondary Educ. Comp." if n==3
   replace Variables="Employed" if n==4
   replace Variables="Monthly Income (US dollars)" if n==5
   replace Variables="Married" if n==6
   replace Variables="Number of Children" if n==7
   replace Variables="\% of respondents with at least one kid" if n==8
   replace Variables="Number of obs." if n==9
   drop n

   //merge with HHSurvey average (from Lupe's work)
   merge 1:1 Variables using "$dir/Data/HHSurvey.dta", keepusing (`x'_m `x'_n)

   swaprows, swap(3) and(4)
   swaprows, swap(9) and(4)
   swaprows, swap(6) and(7)   
   swaprows, swap(7) and(10)
   swaprows, swap(8) and(9)
   swaprows, swap(9) and(10)

   drop _merge
   drop A_`x'2 A_`x'4
   rename *`x'* *A* 
   tempfile `x'
   save ``x''
   }
   
   // Table for AR, BR and CL
   use `AR', clear
   append using `BR'
   append using `CL'

   rename A_A1 nw_mean
   rename A_A3 w1_mean
   rename A_A5 w2_mean
   rename A_A6 ss_n
   rename A_m hh_mean
   rename A_n hh_n

    foreach j in nw w1 w2 hh{
   gen aux = string(`j'_mean, "%10.2f")
   replace aux = "" if aux=="."
   drop `j'_mean
   ren aux `j'_mean
  }
  
        foreach j in ss hh{
   gen aux = string(`j'_n, "%10.0f")
   replace aux = "" if aux=="."
   drop `j'_n
   ren aux `j'_n
  }
  
  order Variables nw_mean w1_mean w2_mean ss_n hh_mean hh_n
  
  replace nw_mean="1207" if _n==10
  replace nw_mean="1201" if _n==20
  replace nw_mean="1200" if _n==30

  
  replace w1_mean="1207" if _n==10
  replace w1_mean="1201" if _n==20
  replace w1_mean="1200" if _n==30
  
  replace w2_mean="1207" if _n==10
  replace w2_mean="1201" if _n==20
  replace w2_mean="1200" if _n==30
  
  replace hh_mean="75467" if _n==10
  replace hh_mean="244307" if _n==20
  replace hh_mean="139379" if _n==30
  drop ss_n hh_n
  
  //column names
  gen n=_n 
  gen Panel="" 
  order n Panel
  replace Panel="Panel" if n==1
  replace Panel="Argentina" if n==2
  replace Panel="Brazil" if n==12
  replace Panel="Chile" if n==22
  label var nw_mean "Mean"
  label var w1_mean "Weighted Mean (age-gender)"
  label var w2_mean "Weighted Mean (age-gender-educ)"
  label var hh_mean "Weighted Mean"

  //drop w1 column: we are not longer showing this column
  drop w1_mean
  replace nw_mean="(1)" if n==1
  replace w2_mean="(2)" if n==1
  replace hh_mean="(3)" if n==1
  
  tempfile Left
  save `Left', replace

  //Appendix Table 2 for CO, MX and PE
   use `CO', clear
   append using `MX'
   append using `PE'

   rename A_A1 nw_mean
   rename A_A3 w1_mean
   rename A_A5 w2_mean
   rename A_A6 ss_n
   rename A_m hh_mean
   rename A_n hh_n
   
   //string variables with 2 decimals
    foreach j in nw w1 w2 hh{
   gen aux = string(`j'_mean, "%10.2f")
   replace aux = "" if aux=="."
   drop `j'_mean
   ren aux `j'_mean
  }
  
  //string variables with no decimals
        foreach j in ss hh{
   gen aux = string(`j'_n, "%10.0f")
   replace aux = "" if aux=="."
   drop `j'_n
   ren aux `j'_n
  }
  
  order Variables nw_mean w1_mean w2_mean ss_n hh_mean hh_n

  replace nw_mean="1209" if _n==10
  replace nw_mean="1202" if _n==20
  replace nw_mean="1210" if _n==30

  
  replace w1_mean="1209" if _n==10
  replace w1_mean="1202" if _n==20
  replace w1_mean="1210" if _n==30
  
  replace w2_mean="1209" if _n==10
  replace w2_mean="1202" if _n==20
  replace w2_mean="1210" if _n==30
  
  replace hh_mean="118916" if _n==10
  replace hh_mean="154247" if _n==20
  replace hh_mean="68509" if _n==30
  drop ss_n hh_n

  //rename column names
  gen n=_n 
  gen Panel="" 
  order n Panel
  replace Panel="Colombia" if n==2
  replace Panel="Mexico" if n==12
  replace Panel="Peru" if n==22
  label var nw_mean "Mean"
  label var w1_mean "Weighted Mean (age-gender)"
  label var w2_mean "Weighted Mean (age-gender-educ)"
  label var hh_mean "Weighted Mean"
  
  //drop w1 column: we are not longer showing this column
  drop w1_mean
  replace nw_mean="(4)" if n==1
  replace w2_mean="(5)" if n==1
  replace hh_mean="(6)" if n==1
  rename (Panel nw_mean w2_mean hh_mean) (Panel2 nw_mean2 w2_mean2 hh_mean2)
  *drop n
  tempfile Right
  save `Right'
  use `Left', clear
  merge 1:1 n using `Right', nogen
  drop if inlist(n,9,10,19,20,29,30)
  drop n
  order Variables
  replace Panel = "" in 1
  drop in 1
  replace Variables = "\hline \addlinespace " + Variables in 1

# delimit ;	
 texsave using "$dir/Results/Table_Descrip_HH1and2.tex",
 headerlines("
 && \multirow{2}{*}{Mean} & Weighted Mean & Weighted Mean && \multirow{2}{*}{Mean} & Weighted Mean & Weighted Mean \\\addlinespace
 &&& (age-gender-education) & (Household Surveys) &&& (age-gender-education) & (Household Surveys) \\\cline{3-3}\cline{4-4}\cline{5-5}\cline{7-7}\cline{8-8}\cline{9-9} \addlinespace
 && (1) & (2) & (3) && (4) & (5) & (6) \\
 ") 
 replace align(ll@{\extracolsep{8pt}}cccl@{\extracolsep{8pt}}ccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Table_Descrip_HH1and2.tex")
restore

*********** Effects of service quality, income, and provider type on choices and willingness to pay (Table B1) ****************

////// Treatments: Being Assigned High Income, High Quality and Private Option 
///// Models
preserve
replace willingness_pay_private_school = ln(1+willingness_pay_private_school)
replace willingness_pay_private_hospital = ln(1+willingness_pay_private_hospital)
local i=1
local mode replace
foreach institution in "school" "hospital" {
    foreach outcome in "final" "willingness_pay" {

		// Control group mean and SD
		sum `outcome'_private_`institution' if initial_private_`institution' == 0 ///
			& high_income_`institution' == 0 ///
			& high_quality_`institution' == 0 
		local mean = r(mean)
		local sd   = r(sd)

		// Main regression
		areg `outcome'_private_`institution' ///
			i.high_quality_`institution'##i.high_income_`institution'##i.initial_private_`institution' ///
			$cov_dem $cov_games, absorb(country)
		local N = e(N)
		
		// Conditional outreg options
        if "`outcome'" == "willingness_pay"{
			local outregopts "dec(3) label bracket excel nocons nor2 noobs nonotes dta slow(2000)"
		}
		else {
			local outregopts "dec(3) label bracket excel nocons nor2 noobs nonotes dta slow(2000)"
		}

		// Export marginal effects instead of raw coefficients
		outreg2 using "$dir/Results/Effects.xml", `mode' `outregopts' ///
			addstat("Control mean", `mean', "Control S.D.", `sd', "Observations", `N') 
		 

		local mode append
		local i=`i'+1
	}
}

rename final_private_school              y1
rename willingness_pay_private_school    y2
rename final_private_hospital            y3
rename willingness_pay_private_hospital  y4

rename high_quality_school q_s
rename high_income_school  inc_s
rename initial_private_school priv0_s
rename high_quality_hospital q_h
rename high_income_hospital  inc_h
rename initial_private_hospital priv0_h

gen qy_s  = q_s*inc_s
gen qp_s  = q_s*priv0_s
gen yp_s  = inc_s*priv0_s
gen qyp_s = q_s*inc_s*priv0_s

gen qy_h  = q_h*inc_h
gen qp_h  = q_h*priv0_h
gen yp_h  = inc_h*priv0_h
gen qyp_h = q_h*inc_h*priv0_h

local X q_s inc_s priv0_s qy_s qp_s yp_s qyp_s ///
        q_h inc_h priv0_h qy_h qp_h yp_h qyp_h

rwolf y1 y2 y3 y4, indepvar(`X') controls($cov_dem $cov_games) ///
      reps(250) method(areg) abs(country)

matrix M = e(RW_q_s)[1...,3]' \ e(RW_inc_s)[1...,3]' \ e(RW_priv0_s)[1...,3]' \ e(RW_qy_s)[1...,3]' \ ///
e(RW_qp_s)[1...,3]' \ e(RW_yp_s)[1...,3]' \ e(RW_qyp_s)[1...,3]'

clear
svmat M	  
rename (M1 M2 M3 M4) (v2 v3 v4 v5)
tostring v*, format(%9.3fc) replace force
replace v2 = "\{"+v2+"\}"
replace v3 = "\{"+v3+"\}"
replace v4 = "\{"+v4+"\}"
replace v5 = "\{"+v5+"\}"
save "$dir/Results/RW_stars.dta", replace
restore

 

 preserve
 use "$dir/Results/Effects_dta.dta", clear
 gen n = _n
 drop if inrange(n,1,2) | inrange(n,8,13) | inrange(n,18,23) | inrange(n,26,31) | inrange(n,34,47)
 drop if inrange(n,50,97) | inrange(n,102,107) | inrange(n,112,117) | inrange(n,120,125) | inrange(n,128,141)
 forvalues i = 4/5{
 	replace v`i' = v`i'[_n+14] if _n>=2 & _n<=15
 }
 drop if inrange(n,98,143)
 
 replace v1="High Quality" if v1=="high_quality_school = 1" 
 replace v1="High Income" if v1=="high_income_school = 1"
 replace v1="Private Default" if v1=="initial_private_school = 1"
 replace v1="High Income × High Quality" if v1=="1.high_quality_school#1.high_income_school"
 replace v1="High Quality × Private Default" if v1=="1.high_quality_school#1.initial_private_school"
 replace v1="High Income × Private Default" if v1=="1.high_income_school#1.initial_private_school"
 replace v1="High Quality × High Income × Private Default" if v1=="1.high_quality_school#1.high_income_school#1.initial_private_school"
 
 swaprows, swap(6) and(8)
 swaprows, swap(7) and(9)
 
 append using "$dir/Results/RW_stars.dta", force
 
 replace n = _n
 forvalues i=20/26{
 	local j = 2*`i' - 36.5
 	replace n = `j' in `i'
 }
 sort n
 
 insobs 3, after(26)
 
 replace v1="Socio-demographic" if _n==28
 replace v1="Other games" if _n==29
 
 forvalues i = 2/5{
 	replace v`i'="Yes" if _n==28 | _n==29
 }

 local h=1 
 foreach i in 2 3 4 5{
	label var v`i' "(`h')"
	local ++h
 }  
 
 insobs 1, before(2)
 insobs 1, before(12)
 insobs 1, before(22) 
 
 replace v1="\textit{Panel A: Main Effects}" in 2
 replace v1="\cline{2\--3} \cline{4\--5} \textit{Panel B: Two-Way Interactions}" in 12
 replace v1="\cline{2\--3} \cline{4\--5} \textit{Panel C: Full Interaction}" in 22
 
 replace v1="\hspace{8pt} "+v1 if inlist(_n,3,6,9,13,16,19,23)
 replace v1="\addlinespace "+v1 if inlist(_n,3,13,23)
 drop in 1
 
   # delimit ;	
 texsave v* using "$dir/Results/Effects.tex",
 headerlines("
  & \multicolumn{2}{c}{School} & \multicolumn{2}{c}{Hospital} \\\cline{2-3}\cline{4-5}\addlinespace
  & Chooses Private & Willingness to Pay & Chooses Private & Willingness to Pay \\\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\addlinespace
  & (1) & (2) & (3) & (4) \\\addlinespace\hline
 ")  
 replace align(l@{\extracolsep{4pt}}cccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Effects.tex")
 #delimit cr
 restore

     *********** Marginal effects of stated institutional trust on choices and willingness to pay across treatments (Table B2) *************
 
 local mode replace

foreach institution in school hospital {

    if "`institution'" == "school" {
        local trustvar   trust_school
        local trustvar2  trust_school_2
    }
    else if ("`institution'" == "hospital") {
        local trustvar   trust_hospital
        local trustvar2  trust_hospital_2
    }

    foreach outcome in final willingness_pay {

        sum `outcome'_private_`institution' ///
            if initial_private_`institution' == 0 ///
            &  high_income_`institution'   == 0 ///
            &  high_quality_`institution' == 0
        local mean = r(mean)
        local sd   = r(sd)

        areg `outcome'_private_`institution' ///
            i.high_quality_`institution'##i.high_income_`institution'##i.initial_private_`institution' ///
            ///
            c.`trustvar'##(i.high_quality_`institution' i.high_income_`institution' i.initial_private_`institution') ///
            c.`trustvar2'##(i.high_quality_`institution' i.high_income_`institution' i.initial_private_`institution') ///
            ///
            $cov_dem $cov_games, absorb(country)

        local N = e(N)

        * Marginal means at low vs high trust levels
		margins high_quality_`institution'##high_income_`institution'##initial_private_`institution', ///
		dydx(`trustvar')		

        estpost margins initial_private_`institution'##high_income_`institution'##high_quality_`institution', ///
		dydx(`trustvar')

        if "`outcome'" == "willingness_pay"{
            local outregopts "dec(1) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
        }
        else {
            local outregopts "dec(3) label bracket excel nocons noaster nor2 noobs nonotes dta slow(2000)"
        }

        outreg2 using "$dir/Results/Marginal_Effects_IT_Continuous_NL.xml", ///
            `mode' `outregopts' ///
            addstat("Control mean", `mean', "Control S.D.", `sd', "Observations", `N')

        local mode append
    }
}
 
 preserve
 use "$dir/Results/Marginal_Effects_IT_Continuous_NL_dta.dta", clear
 gen n = _n
 drop if inrange(n,1,2) | inrange(n,4,39) | inrange(n,56,91) | inrange(n,110,111)
 forvalues i = 4/5{
 	replace v`i' = v`i'[_n+16] if _n>=2 & _n<=17
 }
 drop if inrange(n,92,107)

 replace v1="Public × Low Income × Low Quality" if v1=="0bn.initial_private_school#0bn.high_income_school#0bn.high_quality_school" 
 replace v1="Private × Low Income × Low Quality" if v1=="1.initial_private_school#0bn.high_income_school#0bn.high_quality_school"
 replace v1="Public × High Income × Low Quality" if v1=="0bn.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="Public × Low Income × High Quality" if v1=="0bn.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="Private × High Income × Low Quality" if v1=="1.initial_private_school#1.high_income_school#0bn.high_quality_school"
 replace v1="Private × Low Income × High Quality" if v1=="1.initial_private_school#0bn.high_income_school#1.high_quality_school"
 replace v1="Public × High Income × High Quality" if v1=="0bn.initial_private_school#1.high_income_school#1.high_quality_school"
 replace v1="Private × High Income × High Quality" if v1=="1.initial_private_school#1.high_income_school#1.high_quality_school"
 
 insertrow, place(after) row(19)
 insertrow, place(after) row(19)
 insertrow, place(after) row(19)
 
 replace v1="Socio-demographic" if _n==21
 replace v1="Other games" if _n==22
 
 forvalues i = 2/5{
 	replace v`i'="Yes" if _n==21 | _n==22
 }

 local h=1 
 foreach i in 2 3 4 5{
	label var v`i' "(`h')"
	local ++h
 }  
 
 insobs 1, before(2)
 insobs 1, before(11)
 
 replace v1="\textit{Panel A: Public Default}" in 2
 replace v1="\cline{2\--3} \cline{4\--5} \textit{Panel B: Private Default}" in 11
 
 replace v1="\hspace{8pt} "+v1 if inlist(_n,3,5,7,9,12,14,16,18)
 replace v1="\addlinespace "+v1 if inlist(_n,3,12)
 drop in 1
 
   # delimit ;	
 texsave v* using "$dir/Results/Marginal_Effects_Stated_Trust.tex",
 headerlines("
  & \multicolumn{2}{c}{School} & \multicolumn{2}{c}{Hospital} \\\cline{2-3}\cline{4-5}\addlinespace
  & Chooses Private & Willingness to Pay & Chooses Private & Willingness to Pay \\\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\addlinespace
  & (1) & (2) & (3) & (4) \\\addlinespace\hline
 ")  
 replace align(l@{\extracolsep{4pt}}cccc) location(h) frag nonames nofix 
 ; # delimit cr
 tex_edits, file("$dir/Results/Marginal_Effects_Stated_Trust.tex")
 #delimit cr
 restore

  ************************* Tests of Equality of Marginal Effects by Institutional Trust (Table B3) *****************************
 

local i=1
local mode replace
foreach institution in school hospital {
   foreach outcome in final willingness_pay {
		 areg `outcome'_private_`institution' ///
			i.high_`institution'_trust##(i.initial_private_`institution'##i.high_income_`institution'##i.high_quality_`institution') ///
			$cov_dem $cov_games, absorb(country)
			
		 margins high_`institution'_trust, ///
			at(high_quality_`institution'=(0 1) ///
			   high_income_`institution'=(0 1) ///
			   initial_private_`institution'=(0 1)) ///
			contrast(post)
		
		mat A`i' = r(table)[4,1..8]' 
		local i=`i'+1
   }		
}
mat A = A1, A2, A3, A4
preserve
	clear
	svmat A
	tostring A*, format(%9.3f) replace force
	gen A0 = "", before(A1)
	replace A0 = "Public × Low income × Low quality"  in 1
	replace A0 = "Public × Low income × High quality" in 2
	replace A0 = "Public × High income × Low quality" in 3
	replace A0 = "Public × High income × High quality" in 4
	replace A0 = "Private × Low income × Low quality"  in 5
	replace A0 = "Private × Low income × High quality" in 6
	replace A0 = "Private × High income × Low quality" in 7
	replace A0 = "Private × High income × High quality" in 8
	
	insobs 1, before(1)
	insobs 1, before(6)
	
	insobs 5
	
	replace A0="Observations" in 12	
	replace A1="4169, 3060" in 12
	replace A2="1840, 790" in 12
	replace A3="3780, 3449" in 12
	replace A4="1578, 944" in 12
	
	replace A0="Socio-demographic" if _n==14
	replace A0="Other games" if _n==15
	 
	forvalues i = 1/4{
		replace A`i'="Yes" if _n==14 | _n==15
	}
	
	replace A0="\textit{Panel A: Public Default}" in 1
	replace A0="\cline{2\--3} \cline{4\--5} \textit{Panel B: Private Default}" in 6
	
	replace A0="\hspace{8pt} "+A0 if inlist(_n,2,3,4,5,7,8,9,10)
	replace A0="\addlinespace"+A0 if inlist(_n,2,6,7)
		
	# delimit ;	
	texsave A* using "$dir/Results/Marginal_Effects_Institutional_Trust_Pvalues.tex",
	headerlines("
	& \multicolumn{2}{c}{School} & \multicolumn{2}{c}{Hospital} \\\cline{2-3}\cline{4-5}\addlinespace
	& Chooses Private & Willingness to Pay & Chooses Private & Willingness to Pay \\\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\addlinespace
	& (1) & (2) & (3) & (4) \\\addlinespace\hline
	")  
	replace align(l@{\extracolsep{4pt}}cccc) location(h) frag nonames nofix 
	; # delimit cr
	tex_edits, file("$dir/Results/Marginal_Effects_Institutional_Trust_Pvalues.tex")
	#delimit cr
	
restore

  ********************************************************* Others *********************************************************

 //Joint F-test of equality of mean baseline characteristics across all eight treatment groups.
 global balance "age female secondary_complete employment_situation ln_monthly_income_ppp2019 married number_children children "
 encode country, gen(country2)
 mvreg $balance = i.vigroup i.country2
 testparm i.vigroup
 * Pvalue F test = 0.96

//Footnote 1
 sum willingness_pay_private_school willingness_pay_private_hospital
 count if willingness_pay_private_school == 0
 count if willingness_pay_private_hospital == 0
 * WTP school: Mean = 138.5, SD = 161.7, Share of Zeroes = 9/2630 = 0.34% 
 * WTP hospital: Mean = 90.6, SD = 228.6, Share of Zeroes = 10/2522 = 0.4% 